<template>
  <div class="standard-popup">
    <div class="nav-bar">
      <van-nav-bar
        title="选择规格"
        left-arrow
        @click-left="onClickLeft"
        fixed
        placeholder
        safe-area-inset-top
      ></van-nav-bar>
    </div>

    <!-- 规格选择区域 -->
    <div class="standard-content">
      <div class="standard-item" v-for="item in speInfo.attributes">
        <div class="item-label">
          <span v-if="item.required == 1" class="required">*</span>
          <span class="label"
            >{{ item.attributeName }}<van-icon v-show="false" name="arrow-down"></van-icon
          ></span>
        </div>
        <van-checkbox class="item-status" v-model="item.selected"></van-checkbox>
      </div>

      <div class="standard-item-next" v-if="qualityOptions.length > 0">
        <div class="label">品质要求<span>（选填）</span></div>
        <div class="tag-list">
          <van-tag
            :class="[item.selected ? 'selected' : '']"
            class="van-hairline--surround"
            v-for="(item, index) in qualityOptions"
            :key="item.dictLabel"
            @click="toggleSelection(item, index, 1)"
          >
            {{ item.dictValue }}
          </van-tag>
        </div>
      </div>
      <div class="standard-item-next" v-if="speInfo.plantAttributes.length > 0">
        <div class="label">种植类型<span>（选填）</span></div>
        <div class="tag-list">
          <van-tag
            :class="[item.selected ? 'selected' : '']"
            class="van-hairline--surround"
            v-for="(item, index) in speInfo.plantAttributes"
            :key="item.plantAttributeId"
            @click="toggleSelection(item, index, 2)"
          >
            {{ item.plantAttributeName }}
          </van-tag>
        </div>
      </div>
    </div>

    <!-- 底部确认按钮 -->
    <div class="popup-footer">
      <van-button type="primary" block @click="onSubmit">提交</van-button>
    </div>

    <!-- 米径弹窗 -->
    <common-picker
      v-model:show="showPicker"
      :title="title"
      :columns="deadlineColumns"
      :model-value="pickerValue"
      @confirm="onConfirm"
    />
  </div>
</template>

<script lang="ts" setup>
import CommonPicker from './CommonPicker.vue'
import { ref, watch, defineExpose } from 'vue'
import { getProductCategoryAttributesV2, dictData } from '@/api'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  baseProductId: {
    type: String,
    default: ''
  },
  seedingIndex: {
    type: Number,
    default: 0
  },
  quality: {
    type: String,
    default: ''
  },
  plantAttributeId: {
    type: String,
    default: ''
  },
  attributes: {
    type: Array,
    default: []
  }
})

const emit = defineEmits(['update:show', 'confirm'])

// 米径
const deadlineColumns = [
  { text: '3天', value: 3 },
  { text: '7天', value: 7 },
  { text: '15天', value: 15 },
  { text: '30天', value: 30 },
  { text: '60天', value: 60 }
]

// 规格信息
const speInfo = ref({
  categoryName: '',
  plantAttributes: [],
  categoryId: '',
  attributes: []
})

const showPicker = ref(false)
const title = ref('')
const type = ref()
const pickerValue = ref<number[]>([])
// 品质要求信息
const qualityOptions = ref([])

onMounted(async () => {
  qualityOptions.value = await getDictData('es_product_quality')
})

// 获取规格信息
const getSpeInfoData = async () => {
  try {
    const res = await getProductCategoryAttributesV2({
      baseProductId: props.baseProductId
    })
    if (res.code === 200) {
      speInfo.value = res.data[0]
      speInfo.value.attributes.map((item) => {
        item.selected = false
      })
      speInfo.value.plantAttributes.map((item) => {
        item.selected = false
        if (props.plantAttributeId && props.plantAttributeId === item.plantAttributeId) {
          item.selected = true
        }
      })
      if (props.attributes.length > 0) {
        speInfo.value.attributes = props.attributes
      }
    }
  } catch (error) {
    console.error('获取规格信息失败:', error)
  }
}

// 获取品质信息
const getDictData = async (type) => {
  let { code, data } = await dictData(type)
  if (code === 200) {
    data.map((item) => {
      item.selected = false
      if (props.quality && props.quality === item.dictLabel) {
        item.selected = true
      }
    })
    return data
  }
}

// 监听 baseProductId 变化
watch(
  () => props.baseProductId,
  (newVal) => {
    if (newVal) {
      getSpeInfoData()
    }
  },
  { immediate: true }
)

// 定义组件事件
const toggleSelection = (item: any, index: number, type: number) => {
  if (type === 1) {
    qualityOptions.value.map((quality, idx) => {
      if (idx === index) {
        item.selected = !item.selected
      } else {
        quality.selected = false
      }
    })
  } else {
    speInfo.value.plantAttributes.map((plant, idx) => {
      if (idx === index) {
        item.selected = !item.selected
      } else {
        plant.selected = false
      }
    })
  }
}

// 关闭弹窗
const onClickLeft = () => {
  emit('update:show', false)
}

// 打开米径，地径选择弹窗
const handlePop = (data: number) => {
  type.value = data
  showPicker.value = true
  title.value = data === 1 ? '米径' : '地径'
}

// 求购期限选择
const onConfirm = (selectedValues: any) => {}

// 确认选择
const onSubmit = () => {
  let quality = qualityOptions.value.find((item) => item.selected)
  let category = speInfo.value.plantAttributes.find((item) => item.selected)
  let res = speInfo.value.attributes.filter((item) => item.selected)
  if (res.length > 0) {
    emit('confirm', speInfo.value.attributes, quality, category, props.seedingIndex)
    emit('update:show', false)
  } else {
    showToast('至少选择一种规格')
  }
}

const updateInfo = () => {
  console.log(1)
}

defineExpose({ updateInfo })
</script>

<style lang="scss" scoped>
.standard-popup {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f5f5;
  padding-top: constant(safe-area-inset-top); /* 标准 */
  padding-top: env(safe-area-inset-top); /* iOS 11.0+ */
  :deep(.nav-bar) {
    .van-nav-bar__arrow {
      color: #222;
      font-size: 17px;
    }

    .van-nav-bar__title {
      font-size: 17px;
      font-weight: normal;
      color: #222;
    }
  }

  .standard-content {
    flex: 1;
    overflow-y: auto;

    .standard-item {
      padding: 12px;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      line-height: 21px;
      background: #fff;

      .item-label {
        display: flex;
        font-size: 15px;
        color: #222222;

        .required {
          color: #ea0000;
          font-weight: bold;
        }

        .label {
          display: flex;
          align-items: center;
          gap: 6px;
        }
      }

      .van-icon {
        border-color: #ccc;
      }

      :deep(.van-checkbox__icon--checked .van-icon) {
        color: #fff;
        background: #32bc05;
        border-color: #32bc05;
      }
    }

    .standard-item-next {
      padding: 15px 12px;
      background: #fff;

      .label {
        font-size: 15px;
        color: #222;

        span {
          color: #999999;
        }
      }

      .tag-list {
        margin-top: 10px;
        display: flex;
        align-items: center;
        gap: 10px;
        flex-wrap: wrap;

        .van-tag {
          padding: 0 20px;
          font-size: 12px;
          line-height: 28px;
          font-weight: 400;
          color: #32bc05;
          background: #fff;

          &.selected {
            background: #32bc05;
            color: #fff;
          }
        }

        :deep(.van-tag::after) {
          border-color: #32bc05;
          border-radius: 4px;
        }
      }
    }
  }

  .popup-footer {
    background: #fff;
    padding: 8px 12px;
    border-top: 1px solid #eee;

    :deep(.van-button) {
      height: 45px;
      border-radius: 23px;
      font-size: 16px;
      background-color: #32bc05;
      border-color: #32bc05;
    }
  }
}
</style>
